package cz.muni.fi.pb162.project.db;

import java.io.IOException;
import java.net.NoRouteToHostException;
import java.net.UnknownHostException;

/**
 * Serves for (fictitious) storage of graphical objects to a distant host server.
 * 
 * @author Martin Pasko
 * @version 12_11_2012
 */
public class MyStorage implements Storage
{
    private Connector connector;
    private int maxAttempts;

    /**
     * Gets and saves the connector to a distant host server.
     * 
     * @param connector a connector to a distant host server
     * @ maxAttempts number of attempts to connect before an exception is thrown
     */
    public MyStorage(Connector connector, int maxAttempts) {
        if(connector == null) {
            throw new IllegalArgumentException("connector");
        }
        if(maxAttempts < 1) {
            throw new IllegalArgumentException("maxAttempts");
        }
        this.connector = connector;
        this.maxAttempts = maxAttempts;
    }
    
    public void store(String host, Object data) throws DbException {
        Connection connection;
        try {
            connection = connector.getConnection(host);        
        } catch(UnknownHostException uhe) {
            throw new DbUnreachableException("Nepodarilo sa nadviazat spojenie s "+host+"." ,uhe);
        } catch(NoRouteToHostException nrthe) {
            throw new DbUnreachableException("Nepodarilo sa nadviazat spojenie s "+host+"." ,nrthe);
        }
        
        while(true) {
            int i = 0;
            try {
                connection.sendData(data);
                return;
            } catch(IOException ioe) {
                if(++i >= maxAttempts) {
                    throw new CannotStoreException("Chyba pri prenasani dat.", ioe);
                }
            }
        }
        
    }
    
}
